/*
** map.c for  in /home/guicqu_g//rush/epikong/etape_1
** 
** Made by gallien guicquero
** Login   <guicqu_g@epitech.net>
** 
** Started on  Fri Mar 25 20:58:11 2011 gallien guicquero
** Last update Sun Mar 27 20:24:35 2011 gallien guicquero
*/

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include "get_next_line.h"

int		map_lines(char **map)
{
  int		lines;

  lines = 0;
  while (*map)
    {
      ++map;
      ++lines;
    }
  return (lines);
}

char		**add_line_to_map(char **map, char *line)
{
  char		**new;
  int		lines;
  int		i;

  lines = (map) ? map_lines(map) : 0;
  new = my_malloc((lines + 2) * sizeof(*new));
  i = 0;
  while (i < lines)
    {
      new[i] = map[i];
      ++i;
    }
  new[i] = line;
  free(map);
  new[i + 1] = '\0';
  return (new);
}

char		**map_from_file(char *filename)
{
  char		**map;
  char		*line;
  int		fd;

  if ((fd = open(filename, O_RDONLY)) == -1)
    {
      puts("Fail to open file");
      return (0);
    }
  map = 0;
  while ((line = get_next_line(fd)) != 0)
    map = add_line_to_map(map, line);
  if (close(fd) == -1)
    puts("Warning: Fait to close file");
  return (map);
}

void		map_free(char **map)
{
  int		i;

  if (map)
    {
      i = 0;
      while (map[i])
	{
	  free(map[i]);
	  ++i;
	}
      free(map);
    }
}

char		**map_show(char **map)
{
  int		i;

  if (map)
    {
      i = 0;
      while (map[i])
	puts(map[i++]);
    }
  return (map);
}
